package cn.jhc.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.jhc.bean.Score;
import cn.jhc.dao.ScoreDao;
import cn.jhc.util.HibernateUtil;

public class ScoreDaoImp implements ScoreDao {
	private static final Logger LOG = Logger.getLogger(ScoreDaoImp.class.getName());
	
	@Override
	public void save(Object o) {
		if (o instanceof Score) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("保存失败，请传入" + Score.class.getName() + "的对象。");
	}

	@Override
	public void update(Object o) {
		if (o instanceof Score) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.update(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("更新失败，请传入" + Score.class.getName() + "的对象。");
	}

	@Override
	public void delete(Object o) {
		if (o instanceof Score) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.delete(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("删修失败，请传入" + Score.class.getName() + "的对象。");
	}

	@Override
	public Object get(int id) {
		Score score = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		score = session.get(Score.class, id);
		session.getTransaction().commit();
		return score;
	}

	@Override
	public List list() {
		String hql = "from Score";
		List<Score> scores = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		scores = query.list();
		session.getTransaction().commit();
		
		return scores;
	}

	@Override
	public List list(int start, int count) {
		String hql = "from Score";
		List<Score> scores = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(start + count);
		scores = query.list();
		session.getTransaction().commit();;
		
		return scores;
	}

	@Override
	public long getCount() {
		String hql = "select count(s.scoreid) from Score s";
		Long count = 0l;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		count = (Long) query.uniqueResult();
		session.getTransaction().commit();
		
		return count;
	}

	@Override
	public List<Score> list(Integer sid) {
		String hql = "from Score s where s.student = ?";
		List<Score> scores = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setInteger(0, sid);
		scores = query.list();
		session.getTransaction().commit();
		
		return scores;
	}

}
